package me.algo.n;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author guozheng
 * @date 2024/5/1
 */
public class N2 {
    public static void main(String[] args) {
        var nums = new int[]{1, 7, 3, 6, 5, 6};
        System.out.println(pivotIndex(nums));

    }

    /**
     * LCR 012. 寻找数组的中心下标
     * @param nums
     * @return
     */
    public static int pivotIndex(int[] nums) {
        if (Objects.isNull(nums)) {
            return -1;
        }
        int sum = Arrays.stream(nums).sum();
        int leftSum = 0;
        int rightSum = sum;
        int idx = 0;
        int pre = 0;
        while (idx < nums.length) {
            int cur = nums[idx];
            leftSum += pre;
            rightSum = rightSum - cur;
            if (rightSum == leftSum) {
                return idx;
            }
            idx++;
            pre = cur;
        }
        return -1;
    }
}
